import { TextEncoder } from '../transcoding/encoding'; 
const gbk = require('../transcoding/GbkTextEncoder.js');
const app = getApp()


Page({
  /**
   * 页面的初始数据
   */
  data: {
    receiverText: '',
    receiverLength: 0,
    sendText: '',
    sendLength: 0,
    baifen:0,
    bfBat:0,
    numBat:0,
    time: 0,
    timeStr:"00:00:00",
    power:0,
    eneryP:0,
    enery:0,
    timeSend: false,
  },
  /**
   * 自定义数据
   */
  customData: {
    sendText: '',
    deviceId: '',
    serviceId: '',
    characteristicId: '',
    canWrite: false,
    canRead: false,
    canNotify: false,
    canIndicate: false,
    sendHex:false,
    receiveHex:false,
    time: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const self = this
    this.customData.deviceId = options.deviceId
    this.customData.serviceId = options.serviceId
    this.customData.characteristicId = options.characteristicId
    this.customData.canWrite = options.write === 'true' ? true : false
    this.customData.canRead = options.read === 'true' ? true : false
    this.customData.canNotify = options.notify === 'true' ? true : false
    this.customData.canIndicate = options.indicate === 'true' ? true : false
    console.log("com write is  "+options.write)
    console.log("com read is  "+options.read)
    console.log("com notify is  "+options.notify)
    console.log("com indicate is  "+options.indicate)
    /**
     * 如果支持notify
     */

     const is02Module = options.serviceId == "49535343-FE7D-4AE5-8FA9-9FAFD205E455"
     var characteristicId = ""
     if(is02Module){
        characteristicId =  '49535343-1E4D-4BD9-BA61-23C647249616'
     }else{
       characteristicId = options.characteristicId
     }

    if (options.notify || is02Module) {
      console.log("com characteristicId is "+options.characteristicId)
      wx.notifyBLECharacteristicValueChange({
        deviceId: options.deviceId,
        serviceId: options.serviceId,
        characteristicId,
        state: true,
        success: function(res) {
          // do something...
          console.log("com is start notify !!!")
        },
        fail:function(res){
          console.log("com start notify is fail !!!")
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const self = this;

    function buf2string(buffer) {
      var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
      return arr.map((char, i) => {
        return String.fromCharCode(char);
      }).join('');
    }

    function myHextoString(hex) {
      let out = '';

      for (let i = 0; i < hex.length; i++) {
        let h = (hex[i] / 16);
        console.log("hex i is "+hex[i]);
        if (h >= 10) {
          h = h - 10 + 65;
        } else {
          h = h + 48;
        }
        h = String.fromCharCode(h);
        out += h;
    
        let l = hex[i] % 16;
        if (l >= 10) {
          l = l - 10 + 65;
        } else {
          l = l + 48;
        }
        l = String.fromCharCode(l);
        out += l+" ";
    
      }
      return out
    }
    function isJSON(str) {
          try {
              var obj=JSON.parse(str);
              if(typeof obj == 'object' && obj ){
                  return true;
              }else{
                  return false;
              }
          } catch(e) {
              console.log('error：'+str+'!!!'+e);
              return false;
          }
  }
    function getTimeString(secend)
    {
        let h = Math.floor(secend/3600);
        let mt = secend % 3600;
        let m  = Math.floor(mt/60);
        let s  = secend % 60;
        var str_h="";
        if(h<10)
        {
            str_h = "0" + h.toString();
        }
        else
          str_h = h.toString();
        var str_m = "";
        if(m<10)
        {
            str_m = "0" + m.toString();
        }
        else
            str_m = m.toString()
        var str_s = "";
        if(s<10)
          str_s = "0" + s.toString();
        else  
          str_s = s.toString()
        return str_h + ":" + str_m + ":" + str_s;
    }
    /** 
     * 监听蓝牙设备的特征值变化
     */
    wx.onBLECharacteristicValueChange(function (res) {
      
      const receiverText = buf2string(res.value);
      // console.log("receiveHex is "+self.data.receiveHex);
      var message;
      if(!self.data.receiveHex){
        const buffer = new Uint8Array(res.value);
        message = gbk.decode(buffer);
      }else{
        message = myHextoString(new Uint8Array(res.value));
      }
      console.info(message);
      // console.log("message lenght is "+message.length);
      message =  message.replace(/\'/g,'"')
      if(!isJSON(message))
        return
      var myjson = JSON.parse(message)
      // console.info(myjson["power"])
      self.setData({
        power:myjson["power"],
        eneryP:self.data.eneryP + myjson["power"],
        enery:Math.floor(self.data.eneryP/14),
        numBat:Math.floor(self.data.enery / 1820),
        baifen:Math.floor((self.data.enery % 1820) /1820 * 10000),
        bfBat:Math.floor(self.data.baifen/1000),
        time:self.data.time + 1,
        timeStr:getTimeString(self.data.time)
      })
      console.info(self.data.power)
      for(var i = 0;i<message.byteLength;i++){
        console.log("message is "+message[i])
      }

      self.setData({
        receiverLength: self.data.receiverLength + receiverText.length,
      })
      setTimeout(() => {
        self.setData({
          receiverText: (self.data.receiverText + message).substr(-4000, 4000),
        })
      }, 200)
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.customData.time)
    this.setData({
      receiverText: '',
      receiverLength: 0,
      sendText: '',
      sendLength: 0,
      time: 1000,
      timeSend: false
    })
  },
  /**
   * 更新发送框内容
   */
  updateSendText: function(event) {
    const value = event.detail.value
    this.customData.sendText = value
    this.setData({
      sendText: value
    })
  },
  /**
   * 更新定时发送时间间隔
   */
  updateTime: function(event) {
    const self = this
    const value = event.detail.value
    this.setData({
      time: /^[1-9]+.?[0-9]*$/.test(value) ? +value : 1000
    })
    clearInterval(this.customData.time)
    const deviceId = this.customData.deviceId // 设备ID
    const serviceId = this.customData.serviceId // 服务ID
    const characteristicId = this.customData.characteristicId // 特征值ID
    this.customData.time = setInterval(() => {
      const sendText = self.customData.sendText
      const sendPackage = app.subPackage(sendText) // 数据分每20个字节一个数据包数组
      if (app.globalData.connectState) {
        if (self.customData.canWrite) { // 可写
          self.writeData({ deviceId, serviceId, characteristicId, sendPackage })
        }
      }
    }, self.data.time)
  },
  /**
   * 清除接收
   */
  clearReceiverText: function(event) {
    // this.customData.receiverText = ''
    this.setData({
      receiverText: '',
      receiverLength: 0,
      sendLength: 0
    })
  },

  /*
  *复选按钮
  */ 
  checkboxChange:function(e){
    var send = false;
    var receive = false;

    if(e.detail.value == "send-hex" ){
      send = true
    } else if(e.detail.value == "receive-hex"){
      receive = true
    }else if(e.detail.value == ""){
      console.log("不选")
    }else{
      send = true;
      receive = true;
    }

    this.setData({
      sendHex:send,
      receiveHex:receive,
    })

  },

  /**
   * 清除发送
   */
  clearSendText: function(event) {
    this.customData.sendText = ''
    this.setData({
      sendText: '',
      sendLength: 0
    })
  },


  myStringtoHex: function (str) {
    str = str.toLowerCase();
    console.log("str length is "+str.length);
    let newBuffer = new ArrayBuffer(str.length / 2);
    let hexBuffer = new Uint8Array(newBuffer, 0);
    let h = 0,
      l = 0;
    for (let i = 0; i < str.length / 2; i++) {
      h = str.charCodeAt(2 * i);
  
      l = str.charCodeAt(2 * i + 1);
      if (48 <= h && h <= 57) {
        h = h - 48;
      } else {
        h = h - 97 + 10;
      }
      if (48 <= l && l <= 57) {
        l = l - 48;
      } else {
        l = l - 97 + 10;
      }
      hexBuffer[i] = h * 16 + l;
    }
    return hexBuffer;
  },

  arrayToUint8Array:function (buff){
    const str = String.fromCharCode.apply(null, new Uint8Array(buff));
    var buf = new ArrayBuffer(str.length); // 每个字符占用2个字节
    var bufView = new Uint8Array(buf);
    for (var i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
      console.log("bufView is "+bufView[i]);
    }
    return buf;
  },

  /**
   * 手动发送
   */
  manualSend: function(event) {
    const deviceId = this.customData.deviceId // 设备ID
    const serviceId = this.customData.serviceId // 服务ID
    const characteristicId = this.customData.characteristicId // 特征值ID
    
    const sendText = this.customData.sendText
    let buff;
    if(this.data.sendHex){
      const un = this.myStringtoHex(sendText)
      buff = this.arrayToUint8Array(un);
    }else{
      buff = this.gbkToArray(sendText);
    }

    const sendPackage = app.getSendPackage(buff) // 数据分每20个字节一个数据包数组
    console.log("connectState is "+app.globalData.connectState+"  canWrite is "+this.customData.canWrite);
    //console.log("sendPack length is "+sendPackage.length+"  The sendPackage one is "+sendPackage[0]);
    if (app.globalData.connectState) {
      if (this.customData.canWrite) { // 可写
        this.writeData( deviceId, serviceId, characteristicId, sendPackage )
      }
    } else {
      wx.showToast({
        title: '已断开连接',
        icon: 'none'
      })
    }
  },
  /**
   * 自动发送
   */
  timeChange (event) {
    this.setData({
      timeSend: event.detail.value.length ? true : false
    })
    if (!this.data.timeSend) {
      clearInterval(this.customData.time)
    } else {
      const self = this
      const deviceId = this.customData.deviceId // 设备ID
      const serviceId = this.customData.serviceId // 服务ID
      const characteristicId = this.customData.characteristicId // 特征值ID
      this.customData.time = setInterval(() => {
        const sendText = self.customData.sendText

        let buff;
        if(this.data.sendHex){
          const un = this.myStringtoHex(sendText)
          buff = this.arrayToUint8Array(un);
        }else{
          buff = this.gbkToArray(sendText);
        }
        const sendPackage = app.getSendPackage(buff) // 数据分每20个字节一个数据包数组
        if (app.globalData.connectState) {
          if (self.customData.canWrite) { // 可写
            self.writeData( deviceId, serviceId, characteristicId, sendPackage )
          }
        }
      }, self.data.time)
    }
  },

  //转码
  gbkToArray(content){
    var _encoder = new TextEncoder("gb2312", {NONSTANDARD_allowLegacyEncoding: true});
    // content 需要打印的字符串
    const val = _encoder.encode(content);
    //console.log("gbkToArryval",val);
    return  val.buffer;
  },
  /**
   * 向特征值写数据(write)
   */
  writeData: function (deviceId, serviceId, characteristicId, sendPackage, index = 0) {
    const self = this
    let i = index;
    if(sendPackage == null )
      return;
    let len = sendPackage.length;

    function buf2string(buffer) {
      var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
      return arr.map((char, i) => {
        return String.fromCharCode(char);
      }).join('');
    }

    if (len && len > i) {
      wx.writeBLECharacteristicValue({
        deviceId,
        serviceId,
        characteristicId,
        value: sendPackage[i],
        success: function (res) {
          self.setData({
            sendLength: self.data.sendLength + sendPackage[i].byteLength // 更新已发送字节数
          })
          i += 1;
          self.writeData(deviceId, serviceId, characteristicId, sendPackage, i) // 发送成功，发送下一个数据包
        },
        fail: function (res) {
          console.log("发送失败: "+buf2string(res.value));
          console.log("res.value length is "+new Uint8Array(res.value).length);
          self.writeData(deviceId, serviceId, characteristicId, sendPackage, index) // 发送失败，重新发送
        }
      })
    }
  },

})